package com.dbapp.uilib.widget.titlebar;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.dbapp.uilib.R;
import com.dbapp.uilib.entity.uiMenuItem;
import com.facebook.drawee.view.SimpleDraweeView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import static android.view.Gravity.CENTER;
import static android.view.Gravity.RIGHT;
import static android.view.Gravity.TOP;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.widget.RelativeLayout.ALIGN_LEFT;
import static android.widget.RelativeLayout.ALIGN_RIGHT;
import static com.dbapp.uilib.widget.titlebar.TitleBar.OptionItem.TYPE_IMG_LOCAL;

/**
 * Created by Arirus on 2017/7/26.
 */

public class TitleBar extends LinearLayout {

  public static final int POS_LEFT = ALIGN_LEFT;
  public static final int POS_RIGHT = ALIGN_RIGHT;
  private static final int MAX_ITEM_NUM = 5;//这个值和ids.xml是绑定的，要改一起改；

  public RelativeLayout mRootView;
  public TextView mTitle;
  public LinearLayout mLinearLayoutLeft;
  public LinearLayout mLinearLayoutRight;

  private ArrayList<OptionItem> mListLeft;
  private ArrayList<OptionItem> mListRight;

  private ListMenu mMenu;

  private int mBackgroundColor;
  private int mTxtTitleSize;
  private int mTxtItemSize;
  private int mItemSize;
  private String mTitleContent;
  private int mTitleColor;

  private int curLeftNum;
  private int curRightNum;

  private OnTitleClickListener mTitleClickListener;

  public TitleBar(Context context) {
    this(context, null);
  }

  public TitleBar(Context context,
      @Nullable AttributeSet attrs) {
    this(context, attrs, 0);
  }

  public TitleBar(Context context,
      @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(attrs, defStyleAttr);
  }

  private void init(AttributeSet attrs, int defStyleAttr) {
    View view = LayoutInflater.from(getContext()).inflate(R.layout.titlebar, this);
    mRootView = (RelativeLayout) view.findViewById(R.id.layout_root);
    mTitle = (TextView) view.findViewById(R.id.txt_title);
    mLinearLayoutLeft = (LinearLayout) view.findViewById(R.id.layout_left);
    mLinearLayoutRight = (LinearLayout) view.findViewById(R.id.layout_right);
    mListLeft = new ArrayList<>();
    mListRight = new ArrayList<>();
    mMenu = null;
    curLeftNum = 0;
    curRightNum = 0;

    TypedArray attrsArray = getContext().getTheme()
        .obtainStyledAttributes(attrs, R.styleable.TitleBar, defStyleAttr, 0);
    mBackgroundColor = attrsArray.getColor(R.styleable.TitleBar_background_color,
        getContext().getResources().getColor(android.R.color.holo_blue_bright));
    mTxtTitleSize = attrsArray.getDimensionPixelSize(R.styleable.TitleBar_txt_title_size,
        (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 18,
            getResources().getDisplayMetrics()));
    mTxtItemSize = attrsArray.getDimensionPixelSize(R.styleable.TitleBar_txt_item_size,
        (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16,
            getResources().getDisplayMetrics()));
    mTitleContent = attrsArray.getString(R.styleable.TitleBar_title);
    mTitleColor = attrsArray.getColor(R.styleable.TitleBar_title_color,
        getContext().getResources().getColor(android.R.color.white));

    attrsArray.recycle();

    final TypedArray styledAttributes = getContext().getTheme().obtainStyledAttributes(
        new int[] {android.R.attr.actionBarSize});
    mItemSize = (int) styledAttributes.getDimension(0, 0) * 2 / 3;
    styledAttributes.recycle();

    mTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTxtTitleSize);
    mTitle.setTextColor(mTitleColor);
    mTitle.setText(mTitleContent);
    mRootView.setBackgroundColor(mBackgroundColor);
  }

  public void setTitle(String title) {
    mTitleContent = title;
    mTitle.setText(title);
  }

  public void setBackgroundColor(int color) {
    mRootView.setBackgroundColor(Color.parseColor("#" + Integer.toHexString(color)));
  }

  public void setBackgroundColor(String color) {
    mRootView.setBackgroundColor(Color.parseColor(color));
  }

  private boolean canInsert() {
    int maxNum = Math.max(curLeftNum,curRightNum);
    return maxNum<MAX_ITEM_NUM && (mTitle.getWidth()==0|| mTitle.getWidth() > 200);
  }

  private OptionItem addItemCore(int alignType, LinearLayout curLayout,
      ArrayList<OptionItem> curList) {
    if (!canInsert()) return null;
    OptionItem item = new OptionItem(getContext(), mTxtItemSize);
    LinearLayout.LayoutParams params =
        new LinearLayout.LayoutParams(mItemSize, mItemSize);
    item.setLayoutParams(params);
    if (alignType == POS_LEFT) {
      curLayout.addView(item);
    } else {
      curLayout.addView(item, 0);
    }
    curList.add(item);
    item.setId(OptionItem.getid(POS_LEFT, mListLeft.size()));

    return item;
  }


  public OptionItem addItem(int pos, int type, String content, boolean dot) {
    if (pos == POS_LEFT && curLeftNum < mListLeft.size()) {
      OptionItem itemLeft = mListLeft.get(curLeftNum++);
      itemLeft.setVisibility(VISIBLE);
      itemLeft.change(type, content, dot).refresh();
      return itemLeft;
    } else if (pos == POS_RIGHT && curRightNum < mListRight.size()) {
      OptionItem itemRight = mListRight.get(curRightNum++);
      itemRight.setVisibility(VISIBLE);
      itemRight.change(type, content, dot).refresh();
      return itemRight;
    }
    OptionItem itemLeft = addItemCore(POS_LEFT, mLinearLayoutLeft, mListLeft);

    OptionItem itemRight = addItemCore(POS_RIGHT, mLinearLayoutRight, mListRight);
    if (itemLeft == null || itemRight == null) return null;

    if (pos == POS_LEFT) {
      curLeftNum++;
      itemRight.setVisibility(INVISIBLE);
      itemLeft.change(type, content, dot).refresh();
      return itemLeft;
    }
    curRightNum++;
    itemLeft.setVisibility(INVISIBLE);
    itemRight.change(type, content, dot).refresh();
    return itemRight;
  }

  public OptionItem addItemImba(int pos, int type, String content, boolean dot) {
    ArrayList<OptionItem> curItemList = mListLeft;
    LinearLayout curLayout = mLinearLayoutLeft;
    if (pos == POS_RIGHT) {
      curItemList = mListRight;
      curLayout = mLinearLayoutRight;
    }

    OptionItem item = addItemCore(pos, curLayout, curItemList);
    if (item == null) return null;
    item.change(type, content, dot).refresh();
    return item;
  }

  public void clean(int pos) {
    if (pos == POS_LEFT){
      while (curLeftNum!=0){
        curLeftNum--;
        mListLeft.get(curLeftNum).setVisibility(INVISIBLE);
      }
    }else {
      while (curRightNum!=0){
        curRightNum--;
        mListRight.get(curRightNum).setVisibility(INVISIBLE);
      }
    }
  }

  public OptionItem creatMenu(int resID, ArrayList<uiMenuItem> list) {
    try {
      mMenu = new ListMenu(list, LayoutInflater.from(getContext()).inflate(resID, null), true);
      mMenu.setOutsideTouchable(true);
      mMenu.setBackgroundDrawable(new BitmapDrawable());
    } catch (Exception e) {
      e.printStackTrace();
    }
    OptionItem item = getItem(POS_RIGHT, 1);
    if (item == null) item = addItem(POS_RIGHT, TYPE_IMG_LOCAL, "", false);
    item.change(TYPE_IMG_LOCAL, "", false).refresh();
    return item;
  }

  public void showMenuAsDropDown(View v) {
    int statusBarHeight = -1;
    //获取status_bar_height资源的ID
    int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0) {
      //根据资源ID获取响应的尺寸值
      statusBarHeight = getResources().getDimensionPixelSize(resourceId);
    }
    mMenu.showAtLocation(this, RIGHT | TOP,
        ((RelativeLayout.LayoutParams) v.getLayoutParams()).rightMargin,
        statusBarHeight + getHeight());
  }

  public @Nullable OptionItem getItem(int pos, int index) {
    ArrayList<OptionItem> curItemList = mListLeft;
    if (pos == POS_RIGHT) curItemList = mListRight;

    if (index > curItemList.size()) return null;
    return curItemList.get(index - 1);
  }

  //title 点击事件
  public void setOnTitleClickListener(OnTitleClickListener listener) {
    mTitle.setOnClickListener(listener);
  }

  public void removeOnTitleClickListener() {
    mTitle.setOnClickListener(null);
  }

  public interface OnTitleClickListener extends OnClickListener {
  }

  public ListMenu getMenu() {
    return mMenu;
  }

  public static class OptionItem extends FrameLayout {
    public static final int TYPE_IMG_LOCAL = 2;
    public static final int TYPE_TXT = 1;
    public static final int TYPE_IMG_NET = 3;

    private boolean isShow;
    private int type;
    private String content;

    private int mTxtItemSize;

    public View mainView;
    private dot dotView;

    private static Map<String, Integer> imgMap;

    {
      imgMap = new HashMap<>();
      imgMap.put("back", R.drawable.securitynotice_icon_nav_back);
      imgMap.put("", R.drawable.securitynotice_icon_nav_back);
    }

    public OptionItem(@NonNull Context context, int txtItemSize) {
      super(context);
      init(txtItemSize);
    }

    public OptionItem(@NonNull Context context, int txtItemSize , int type,
        String content, boolean isShow) {
      super(context);
      this.isShow = isShow;
      this.type = type;
      this.content = content;
      init(txtItemSize);
      refresh();
    }

    private void init(int txtItemSize) {
      mainView = null;
      dotView = null;
      //获取文字大小属性
      mTxtItemSize = txtItemSize;
    }

    public OptionItem change(int type, String content, boolean isShow) {
      if (type == this.type) return this;
      this.type = type;
      this.content = content;
      this.isShow = isShow;
      return this;
    }

    private void refresh() {
      if (mainView != null) removeView(mainView);
      //主view
      LayoutParams params = new LayoutParams(MATCH_PARENT, MATCH_PARENT);
      if (type == TYPE_TXT) {
        mainView = new TextView(getContext());
        ((TextView) mainView).setText(content);
        ((TextView) mainView).setTextSize(TypedValue.COMPLEX_UNIT_PX, mTxtItemSize);
        ((TextView) mainView).setGravity(CENTER);
        ((TextView) mainView).setMaxLines(1);
      } else if (TYPE_IMG_NET == type) {
        mainView = new SimpleDraweeView(getContext());
        ((SimpleDraweeView) mainView).setImageURI(content);
      } else if (TYPE_IMG_LOCAL == type) {
        mainView = new SimpleDraweeView(getContext());
        ((SimpleDraweeView) mainView).setImageDrawable(
            getContext().getResources().getDrawable(imgMap.get(content)));
      }
      mainView.setLayoutParams(params);
      //mainView.setPadding(10, 10, 10, 10);
      addView(mainView);
      //红点
      dotView = new dot(getContext());
      ViewGroup.LayoutParams params1 = new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT);
      dotView.setLayoutParams(params1);
      showDot(isShow);
    }

    public void showDot(boolean isShow) {
      this.isShow = isShow;
      if (isShow) {
        addView(dotView);
      } else {
        removeView(dotView);
      }
    }

    public static int getid(int pos, int index) {
      if (pos == POS_LEFT) {
        switch (index) {
          case 1:
            return R.id.title_bar_item_left_1;
          case 2:
            return R.id.title_bar_item_left_2;
          case 3:
            return R.id.title_bar_item_left_3;
          case 4:
            return R.id.title_bar_item_left_4;
        }
      } else if (POS_RIGHT == pos) {
        switch (index) {
          case 1:
            return R.id.title_bar_item_right_1;
          case 2:
            return R.id.title_bar_item_right_2;
          case 3:
            return R.id.title_bar_item_right_3;
          case 4:
            return R.id.title_bar_item_right_4;
        }
      }
      return 0;
    }

    //这个不再调整了
    private static class dot extends View {
      Paint mPaint = new Paint();

      public dot(Context context) {
        super(context);
      }

      @Override protected void onDraw(Canvas canvas) {
        mPaint.setColor(Color.RED);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeWidth(25);
        int width = getWidth();
        int height = getHeight();
        canvas.drawPoint(width * 5 / 6, height / 3, mPaint);
      }
    }
  }
}
